

import inspect
import sys,os,json,time
p=os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
p=os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(p))))
p=p+os.sep+'_base_tool'+os.sep+'python'
sys.path.append(p)
from base_class1_0 import base_class # type: ignore
import sqlite3,yaml,json,copy
#sqlite3 正常调用
# def tool_sqlite_test():
#     ##########################完整创建sqlite3数据库备注
#     # 创建数据库连接
#     conn = sqlite3.connect('example.db')
#     # 创建一个游标对象
#     cursor = conn.cursor()

#     # 创建一个包含所有数据类型的表
#     cursor.execute('''CREATE TABLE example_table
#                 (id INTEGER PRIMARY KEY,
#                 varchar_col VARCHAR(20) NOT None,
#                 text_col TEXT,
#                 integer_col INTEGER,
#                 real_col REAL,
#                 blob_col BLOB,
#                 numeric_col NUMERIC(10,2),
#                 date_col DATE,
#                 time_col TIME,
#                 datetime_col DATETIME,
#                 unique_col INTEGER UNIQUE,
#                 index_col INTEGER,
#                 foreign_key_col INTEGER,
#                 check_col INTEGER CHECK(check_col > 0),
#                 comment_col TEXT)''')
#     # id：主键，表示表中每一行的唯一标识符。数据类型为INTEGER，表示整数类型。范围为-9223372036854775808至9223372036854775807。注意事项：作为主键，不允许为空（NOT None），通常会设置为自增长（AUTOINCREMENT）。
#     # varchar_col：可变长字符字段，最大长度为20个字符。数据类型为VARCHAR(20)，表示可变长度的字符串，最大长度为20个字符。范围根据输入的字符长度而定。注意事项：不允许为空（NOT None）。
#     # text_col：长文本字段，可以存储较长的文本内容。数据类型为TEXT，表示文本类型。范围根据输入的字符长度而定。注意事项：可以为空（None）。
#     # integer_col：整数字段。数据类型为INTEGER，表示整数类型。范围为-2147483648至2147483647。注意事项：可以为空（None）。
#     # real_col：实数字段，可以存储浮点数。数据类型为REAL，表示实数类型。范围根据输入的值而定。注意事项：可以为空（None）。
#     # blob_col：二进制大对象字段，用于存储二进制数据。数据类型为BLOB，表示二进制大对象类型。范围根据输入的二进制数据长度而定。注意事项：可以为空（None）。
#     # numeric_col：数值字段，可以存储固定精度的数字。数据类型为NUMERIC(10,2)，表示数值类型，总共10位，其中2位是小数位。范围根据输入的值而定。注意事项：可以为空（None）。
#     # date_col：日期字段，可以存储日期值。数据类型为DATE，表示日期类型。格式为YYYY-MM-DD。注意事项：可以为空（None）。
#     # time_col：时间字段，可以存储时间值。数据类型为TIME，表示时间类型。格式为HH:MM:SS。注意事项：可以为空（None）。
#     # datetime_col：日期时间字段，可以存储日期和时间值。数据类型为DATETIME，表示日期时间类型。格式为YYYY-MM-DD HH:MM:SS。注意事项：可以为空（None）。
#     # unique_col：唯一字段，值必须唯一。数据类型为INTEGER，表示整数类型。范围为-9223372036854775808至9223372036854775807。注意事项：值必须唯一（UNIQUE）。
#     # index_col：索引字段，用于提高查询效率。数据类型为INTEGER，表示整数类型。范围为-9223372036854775808至9223372036854775807。注意事项：可以为空（None）。通常会在查询中用到该字段时创建索引。
#     # foreign_key_col：外键字段，用于关联其他表的主键。数据类型为INTEGER，表示整数类型。范围为-9223372036854775808至9223372036854775807。注意事项：可以为空（None），通常用于关联其他表的主键。
#     # check_col：检查字段，用于限制值的范围。数据类型为INTEGER，表示整数类型。范围为-9223372036854775808至9223372036854775807。注意事项：可以为空（None），检查条件为大于0（CHECK(check_col > 0)）。
#     # comment_col：注释字段，用于存储注释信息。数据类型为TEXT，表示文本类型。范围根据输入的字符长度而定。注意事项：可以为空（None）。通常用于存储关于数据的注释或说明信息。
#     # 提交更改
#     conn.commit()
#     # 关闭数据库连接
#     conn.close()
import os
import sqlite3
import time
from datetime import datetime
import random
from string import ascii_letters, digits
##############################设置触发器update_add_int  使数据在被更新时 数值自动在区间内递增   step 0/3
set_update_add_int_trigger_val=f'''CREATE TRIGGER update_add_int  
AFTER UPDATE ON ###tablename###  
FOR EACH ROW  
BEGIN  
   UPDATE ###tablename###
   SET   
###val###
   WHERE id = old.id;  
END;'''
set_update_add_int_trigger_val2='''   
      ###a### = CASE  
         WHEN ###a### = ###b### THEN ###c### 
         ELSE ###a### + 1  
      END'''

###############
class a_1_0_1_0_0_base1:
    def cn(self,path):#get_conn_cursor
        conn = sqlite3.connect(path)
        cursor = conn.cursor()
        return cursor,conn
    def create_all_table(self,db_path):
        cur, conn=self.cn(db_path)
        # print('db_path',db_path)
        for item in dir(self):
            if "table__" ==item[:len("table__")]:
                # print("self."+item,'start')
                sql=eval("self."+item)
                try:
                    if "table" not in sql:continue
                except:
                    
                    print('########error1')
                    continue#sql is None :error
                try:
                    # table_name=sql[sql.index("table") + 5:sql.index("(")].strip().replace("IF NOT EXISTS ","")
                    res=cur.execute(sql)
                    conn.commit()  # 将写操作结果提交到数据库
                except Exception as e:
                    print('########error2',e,sql)
        
        for item in dir(self):
            if "index__" ==item[:len("index__")]:
                sql=eval("self."+item)
                try:
                    cur.execute(sql)
                    conn.commit()  # 将写操作结果提交到数据库
                except:pass
            elif "trigger__" ==item[:len("trigger__")]:
                sql=eval("self."+item)
                try:
                    cur.execute(sql)
                    conn.commit()  # 将写操作结果提交到数据库
                except Exception as e:#print('error',e,sql)
                    pass
                # print("create table",table_name,"ok")
        conn.close()
    def delete_all_table(self,db_path):

        cur, conn=self.cn(db_path)
        for item in dir(self):
            if "table_" ==item[:len("table_")]:
                sql = eval("self." + item)
                if "table" not in sql:continue
                sql=sql.replace("IF NOT EXISTS","")
                table_name=sql[sql.index("table") + 5:sql.index("(")].strip()
                delete_sql="DROP TABLE %s ;"%(table_name)
                try:
                    cur.execute(delete_sql)
                    conn.commit()  # 将写操作结果提交到数据库
                    # print("delete table",table_name,"ok")
                except Exception as e:
                    pass
                    # print("delete table",table_name,"error:",e)

        conn.close()
        os.remove(db_path)
        # print("sqlite存储文件已经删除")
    def reset_all_table(self,db_path):
        self.delete_all_table(db_path)
        self.create_all_table(db_path)
    #查找数据,无条件
    def select_info_all(self,cur,conn,table_name,select_field_name=("*")):

        sql="select %s from %s;"%(",".join(select_field_name),table_name)
        # print(sql)

        try:
            cur.execute(sql)
            info=cur.fetchall()#空则为[]
            # conn.commit()
        except:
            info=[]
        conn.close()
        return info
    #查询指定1
    def select_info_from_field(self,cur,conn,table_name,condition_field:dict,select_field_name:list=("*",),limit=None):
        keys, values = zip(*(condition_field.items()))
        sql = "select %s from %s where %s%s;" %(",".join(select_field_name),table_name," and ".join(key+"=?" for key in keys),""if limit is None else (" limit %s"%limit if isinstance(limit,int) else " limit %s,%s"%(limit[0],limit[1])))
        # print(sql)
        try:
            cur.execute(sql,values)
            info = cur.fetchall()  # 空则为[]
            # conn.commit()
        except:
            info = []
        conn.close()
        return info
    #指定时间字段　和limit
    def select_info_from_by_time_and_limit(self,cur,conn,table_name,condition_field:dict=None,limit=(0,10),time_field=("create_time",False),select_field_name:list=("*")):
        values=None
        if condition_field!=None:
            keys, values = zip(*(condition_field.items()))
            sql = "select %s from %s where %s order by datetime(%s) %s limit ?,?;" %(",".join(select_field_name),table_name," and ".join(key+"=?" for key in keys),time_field[0],""if time_field==True else "desc")
        else:
            sql = "select %s from %s  order by datetime(%s) %s limit ?,?;" % (
            ",".join(select_field_name), table_name, time_field[0],
            "" if time_field == True else "desc")
        if values is None:
            values=limit
        else:
            values = list(values)
            values.extend(limit)
        # print(sql)
        try:
            cur.execute(sql,values)
            info = cur.fetchall()  # 空则为[]
            # conn.commit()
        except:
            info = []
        conn.close()
        return info

    #创建数据,[{"key":""}]
    def insert_info_all(self,cur,conn,table_name,info:list,printx=1):
        try:
            for dct in info:
                keys, values = zip(*(dct.items()))
                # print(keys,values)
                sql= "insert into {} ({}) values ({});".format(table_name, ','.join(keys),
                                                          ','.join("?" for _ in range(len(keys)))
                                                             )
                                    
                # print(sql,values)
                cur.execute(sql,values)
            conn.commit()
            conn.close()
            return True
        except Exception as e:
            # print(e)
            conn.close()
            return False
    # 插入所有数据　
    def insert_info_all_lst(self, cur, conn, table_name, info: list):

        try:
            sql = "insert into {} values ({});".format(table_name,
                                                       ','.join("?" for _ in range(len(info)))
                                                       )
            cur.execute(sql, info)
            conn.commit()
        except Exception as e:
            pass
            # print(e)
        conn.close()

    #修改数据
    def update_info(self,cur,conn,table_name,condition_field:dict,change_field:dict):
        try:
            keys2, values2 = zip(*(condition_field.items()))
            keys1, values1 = zip(*(change_field.items()))
            sql= "UPDATE {} SET {} where {};".format(table_name, ",".join(key+"='{}'" for key in keys1), " and ".join(key+"=?" for key in keys2))
            sql=sql.format(*(str(value) for value in values1))
            # print("update",sql)
            cur.execute(sql,values2)
            conn.commit()
        except Exception as e:
            pass
            # print(e)
        conn.close()
    #删除列
    def delete_line(self,cur,conn,table_name,condition_field:dict):
        try:
            keys, values = zip(*(condition_field.items()))
            sql= "delete from {} where {};".format(table_name, " and ".join(key+"=?" for key in keys))
                # print(sql,values)
                # print(sql%values)
            cur.execute(sql,values)
            conn.commit()
        except Exception as e:
            pass
            # print(e)
        conn.close()

    #用户初始化
    def init(s,user_db_path,*args,**kwargs):
        # print('user_db_path',user_db_path)
        s.create_all_table(user_db_path)
        for func in args:
            func(**kwargs)
class a_1_0_1_0_0_base2(a_1_0_1_0_0_base1):
    _number={'0','1','2','3','4','5','6','7','8','9'}
    __isalpha_add='isjksdhf'
    def _replace_key(self,key):
        #替换特殊的字段 如 '1-1' 是不允许使用数字开头 不允许 - ，这里就要进行替换
        key=key.replace('-','_')
        #判断首字符是否是英文，不是的话就添加前缀 self.__isalpha_add
        if key[0].isalpha() is False:
            key= self.__isalpha_add+key
        return key
    def to_json(self,str_):
        try:
            return json.loads(str_)
        except:
            print('$$$','none')
            return ''
    def lambda_f(self,val):
        return lambda :val
    def __init__(self,**kwargs):
        self.test_flag=True
        #获取数据库 建表配置数据
        self.db_data=kwargs.get('db_data',{
                    "base_info": {
                        "index": "5",
                        "vue_name": "a_1_0_2_28_1",
                        "deepcopy_data": {
                            "index": 1,
                            "en_name": "user_db",
                            "ch_name": "用户库",
                            "note": "",
                            "ps": {
                                "1": {
                                    "k": "params1",
                                    "v": "value1"
                                }
                            },
                            "name": "user_db[用户库]"
                        }
                    },
                    "dict": {
                        "1": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "id",
                                    "field_type": "INTEGER",
                                    "default_value": 0,
                                    "ch_name": "",
                                    "index_type": "PRIMARY KEY",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "id[]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "2": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "user_name",
                                    "field_type": "TEXT",
                                    "default_value": "",
                                    "ch_name": "用户名",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "user_name[用户名]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "3": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "passwd",
                                    "field_type": "TEXT",
                                    "default_value": "",
                                    "ch_name": "密码",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "passwd[密码]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "4": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "level",
                                    "field_type": "INTEGER",
                                    "default_value": 0,
                                    "ch_name": "权限等级",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "level[权限等级]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "5": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "create_id",
                                    "field_type": "INTEGER",
                                    "default_value": 0,
                                    "ch_name": "创建人id",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "create_id[创建人id]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        }
                    }
                })
        #获取数据库 建表的表名   没有则获取db_data的键名为表名
        self.table_name=self.db_data['base_info']['deepcopy_data']['en_name']
        #获取数据库 存放数据库文件所在的文件夹 没有则默认为当前文件所在的文件夹
        self.db_dir_path=kwargs.get('db_dir_path',os.path.dirname(os.path.abspath(__file__)))
        #获取数据库 存放数据库文件的具体路径 为存放文件夹+表名+.db
        self.db_file_path=self.db_dir_path+os.sep+self.table_name+'.db'
        # print('self.db_file_path',self.db_file_path)
        #解析配置数据 生成sqlite3的建表数据
        #step -1 根据配置生成字段
        all_field_str=''#存放所有字段
        self.virtual_names='('#创建虚拟数据需要插入字段名
        temp_virtual_names=''
        self.virtual_name_lst=[]
        self.字段输出格式_dct={}
        self.字段输出格式_func={'json':self.to_json}
        self.virtual_types={}#创建虚拟数据 的数据类型
        self.virtual_lens={}#创建虚拟数据的 长度限制范围
        self.default_dct={#数据类型为空时 自动填充内容如下
            'DATETIME':lambda:datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            'INTEGER':lambda :0,
            'TEXT':lambda :'None',
            'VARCHAR':lambda :'None'
        }
        self.id_name=None#主键的名称
        self.field_all_dct={}#存放表内所有字段的 名称 和 类型
        self.field_custom_default={}#默认值
        ##############################设置触发器update_add_int  使数据在被更新时 数值自动在区间内递增   step 1/3
        self.update_add_int=[]
        #############################字段被修改时 自动添加当前字段 和 当前时间  step 0/2
        self.update_modify_time=[]
        for index in self.db_data['dict']:
            field_data=self.db_data['dict'][index]['base_info']["deepcopy_data"]#字段数据
            #字段名称
            key2=field_data['en_name']
            #字段类型
            field_type=field_data['field_type']
            #字段默认值
            default_value=field_data['default_value']
            #索引类型
            index_type=field_data['index_type']

            #保存字段的默认值
            if field_type=="DATETIME":
                self.field_custom_default[key2]=lambda:datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            elif index_type!="PRIMARY KEY":
                self.field_custom_default[key2]=lambda:default_value
            #当前字段添加进所有字段中
            temp_field_str="%s %s %s %s,"%(key2,                                                                                      #字段名称
                                        field_type,                                                                    #字段类型
                                        'PRIMARY KEY' if index_type=='PRIMARY KEY' else '',                                               #是否时主键
                                        'autoincrement' if (index_type=='PRIMARY KEY' and field_type=="INTEGER") else '', 
                                        )
            #自增长
            if (index_type=='PRIMARY KEY' and field_type=="INTEGER"):
                temp_virtual_names+='%s,'%key2
                self.virtual_types[key2]=field_type
                self.virtual_lens[key2]=''
                self.virtual_name_lst.append(key2)
            #主键
            if index_type=='PRIMARY KEY':
                self.id_name=key2
            # if temp_field_dct.get('字段输出格式') is not None:
            #     self.字段输出格式_dct[key2]=temp_field_dct['字段输出格式']
            all_field_str+=temp_field_str
            
            
    #   <el-select v-model="form.index_type" placeholder="请选择索引类型">
    #     <el-option label="None【无】" value="None"></el-option>
    #     <el-option label="PRIMARY KEY【主键】" value="PRIMARY KEY"></el-option>
    #     <el-option label="Unique Index【唯一索引】" value="Unique Index"></el-option>
    #     <el-option label="Index【索引】" value="Index"></el-option>
            #普通索引
            if index_type=='Index':exec('self.index__%s=%s'%(key2,'"create index index__%s on %s(%s);"'%(key2,self.table_name,key2)))
            #唯一索引
            if index_type=="Unique Index" :exec('self.index__%s=%s'%(key2,'"create unique index index__%s on %s(%s);"'%(key2,self.table_name,key2)))
            #如果是时间类型
            ##############################字段被修改时 自动添加当前字段 和 当前时间  step 1/2
            if default_value=='update_time' and field_type=="DATETIME":
                self.update_modify_time.append(key2)#datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        self.filed_name_lst=list(self.field_custom_default.keys())
        self.insert_sql="insert into {} ({}) values ({});".format(self.table_name,','.join(self.filed_name_lst),','.join("?" for _ in range(len(self.filed_name_lst))))
        if all_field_str[-1]==',':all_field_str=all_field_str[:-1]#去除最后的,
        if temp_virtual_names[-1]==',':temp_virtual_names=temp_virtual_names[:-1]#去除最后的,
        self.virtual_names=self.virtual_names+temp_virtual_names+')'
        #创建表 的建表信息
        self.table__info="""create table IF NOT EXISTS %s(%s);"""%(self.table_name,all_field_str)
        #数据库初始化
        #将self.table_和self.index__
        self.init(self.db_file_path)
    #创造虚拟数据
    def _create_cirtual_data(self,field_name):
        field_type=self.virtual_types[field_name]#创建虚拟数据 的数据类型
        field_len=self.virtual_lens[field_name]#创建虚拟数据的 长度限制范围
        field_type=field_type.upper()#全变成大写
        if field_type=='VARCHAR':
            # print('field_len',field_len,type(field_len))
            res= ''.join(random.choices(ascii_letters + digits)) if field_len in [None,False] else ''.join(random.choices(ascii_letters + digits, k=random.randint(*field_len)))
            res='"'+res+'"'
            res='"33"'
            res='"#241342"'
            # print('field_len2',field_len,type(field_len))
        elif field_type=='INTEGER':
            res= random.randint(1, 100)
        elif field_type=='BLOB':#没测试过
            if field_len not in [None,False]:
                lenx=field_len
            else:
                lenx=[0,10]
            res= bytes([random.randint(0, 255) for _ in range(random.randint(*lenx))])
        elif field_type=='NUMERIC':#没测试过
            res= f'{random.randint(1, 100):.2f}'
            res='"'+res+'"'
        elif field_type=='DATE':
            # 获取当前时间
            current_time = datetime.now()
            # 将当前时间转换为指定格式
            formatted_time = current_time.strftime("%Y-%m-%d")
            res='"'+formatted_time+'"'
        elif field_type=='TIME':
            
            # 获取当前时间
            current_time = datetime.now()
            # 将当前时间转换为指定格式
            formatted_time = current_time.strftime("%H:%M:%S")
            res='"'+formatted_time+'"'
        elif field_type=='DATETIME':
            # 将当前时间转换为指定格式
            formatted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            res='"'+formatted_time+'"'
        elif field_type=='TEXT':
            res= ''.join(random.choices(ascii_letters + digits, k=random.randint(1, 5)))
            res='"'+res+'"'
        # print('field_name',field_name,field_type,res)
        return res
    
    def create_virtual_data(self, n=None):
        if n is None:n=random.randint(1,100)
        # 连接到数据库
        conn = sqlite3.connect(self.db_file_path)
        cursor = conn.cursor()

        # 获取表的字段信息
        cursor.execute(f"PRAGMA table_info({self.table_name})")
        fields = cursor.fetchall()
        # print(fields)
        # 生成虚拟数据并插入到表中
        for _ in range(n):
            # print(f"{','.join(['?' for _ in fields[0]])}")
            # print(self.virtual_name_lst)
            # print([eeeee for eeeee in self.virtual_name_lst])
            sql="INSERT INTO %s %s VALUES (%s)"%(self.table_name,self.virtual_names,','.join([str(self._create_cirtual_data(eeeee))for eeeee in self.virtual_name_lst]))
            # print(sql)
            cursor.execute(sql)
            conn.commit()
        conn.close()
        return n
    #查询数据
    def select_field_all(self,select_field_name=("*")):
        # 连接到数据库
        conn = sqlite3.connect(self.db_file_path)
        cursor = conn.cursor()
        sql="select %s from %s;"%(",".join(select_field_name),self.table_name)
        print(sql)

        try:
            cursor.execute(sql)
            info=cursor.fetchall()#空则为[]
            # conn.commit()
        except:
            info=[]
        conn.close()
        return info
    #转字典用
    def dict_factory(self,cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            var_type=self.字段输出格式_dct.get(col[0])
            if var_type is not None:
                val=self.字段输出格式_func[var_type](row[idx])
                print('val',val)
            else:
                val=row[idx]
            d[col[0]] = val

        return d
    def _del1(self,d):#删带空字符的元素 如 [["", 'erqw'], ['rewqrqw'], '']   ->[['rewqrqw']]
        try:
            for i in range(len(d)-1,-1,-1):
                if d[i] in ('',None):
                    del d[i]
                elif isinstance(d[i],list):
                    if '' in d[i] or None in d[i]:
                        del d[i]
            res=d
        except Exception as e:res=d
        return res
    def _post_default(self,names,val):
        pass
    def _post_sql(self,names):
        #names: list
        pass
    def _post_get_names(self,info):#只要不是自增的 都需要插入
        res=[
            [],#[name1,name2,name3]  要插入的字段列表
            {},#{name1:value,name2:value,name3:value}  对应要插入的字段 的默认值
        ]
        #info:dict
        if isinstance(info,dict):#{'name1':val1,'name2':val2}
            for key in self.field_all_dct.keys():#遍历表查看
                #检查是否是自增字段  是自增字段 则不设置默认值
                pass
    def test_print(self,*args,**kwargs):
        if self.test_flag is True:
            print(*args,**kwargs)
    #创建数据
    def post(self,info=None,test=True,**kwargs):
        # if self.table_name=='log_db':self.test_flag=False
        # else:self.test_flag=True
        if test is True:
            self.test_print('post,put,delete,get params########1111111#########:','post')
        if info is None:
            return
        self.test_print('post info:',info)
        #info ： list   批量插入数据
        #           info = [[name1,name2,name3],[val1,val2,val3],[val1,val2,val3]] # [name1,name2,name3]为需要插入的字段名 val1,val2,val3为值
        #           info = [{'name1':val1,'name2':val2},{'name1':val3,'name4':val6}] #为 逐个插入
        #info ： dict   插入单个数据
        #           info = {'name1':val1,'name2':val2}
        #创建cur和conn
        # 连接到SQLite数据库
        conn = sqlite3.connect(self.db_file_path)
        #将数据转为字典
        conn.row_factory = self.dict_factory
        # 创建游标对象
        cursor = conn.cursor()
        if isinstance(info,list) is True:
            if isinstance(info[0],list) is True:#info = [[name1,name2,name3],[val1,val2,val3],[val1,val2,val3]] # [name1,name2,name3]为需要插入的字段名 val1,val2,val3为值
                # self.test_print(info[:3])
                temp_dct={value:index for index, value in enumerate(info[0])}
                new_lst=[]
                for item in info[1:]:
                    lst=[]
                    for item2 in self.filed_name_lst:
                        idx=temp_dct.get(item2)
                        if idx is None:
                            value=self.field_custom_default[item2]()
                        else:
                            value=item[idx]
                        lst.append(value)
                    new_lst.append(lst)
                try:
                    # 使用 executemany() 方法批量插入数据
                    if test is not None:
                        self.test_print('sql:',self.insert_sql)
                        self.test_print('new_lst:',new_lst)
                    conn.executemany(self.insert_sql, new_lst)
                    # 提交更改并关闭连接
                    conn.commit()
                    # 使用lastrowid()获取新插入数据的自增主键值
                    new_rowid = cursor.lastrowid

                    # self.test_print(f"新增数据的自增主键值是：{new_rowid}")
                    conn.close()
                except Exception as e:
                    # self.test_print(e)
                    conn.close()
                    res={'type':'error','message':str(e),'other':'1111'}
                    if test is not None:
                        self.test_print('error333',res)
                    return res
            elif isinstance(info[0],dict) is True:#[{'name1':val1,'name2':val2},{'name1':val3,'name4':val6}] #为 逐个插入
                temp_dct=info[0]
                new_lst=[]
                for item in info:
                    lst=[]
                    for item2 in self.filed_name_lst:
                        value=item.get(item2)
                        if value is None:
                            value=self.field_custom_default[item2]()
                        lst.append(value)
                    new_lst.append(lst)
                try:
                    # 使用 executemany() 方法批量插入数据
                    if test is not None:
                        self.test_print('sql:',self.insert_sql)
                        self.test_print('new_lst:',new_lst)
                    conn.executemany(self.insert_sql, new_lst)
                    # 提交更改并关闭连接
                    conn.commit()
                    # 使用lastrowid()获取新插入数据的自增主键值
                    new_rowid = cursor.lastrowid

                    # self.test_print(f"新增数据的自增主键值是：{new_rowid}")
                    conn.close()
                except Exception as e:
                    # self.test_print(e)
                    conn.close()
                    res={'type':'error','message':str(e),'other':'222'}
                    if test is not None:
                        self.test_print('error111',res)
                    return res
        elif isinstance(info,dict):#info = {'name1':val1,'name2':val2}
            values=[]
            
            for item in self.filed_name_lst:
                
                value=info.get(item)
                if item=='p7_usPara':
                    print('#############self.field_custom_default',self.field_custom_default)
                    print('item',item)
                    print(self.field_custom_default['p7_usPara']())
                if value is None  or value=='':value=self.field_custom_default[item]()
                values.append(value)
            try:
                # self.test_print('values',values)
                self.test_print('sql:',self.insert_sql)
                self.test_print('values:',values)
                cursor.execute(self.insert_sql,values)
                conn.commit()
                new_rowid = cursor.lastrowid
                # new_rowid=1
                # self.test_print(f"新增数据的自增主键值是：{new_rowid}")
                conn.close()
            except Exception as e:
                # self.test_print(e)
                conn.close()
                res={'type':'error','message':str(e),'other':'333'}
                self.test_print('error222',res)
                return res
        return {'type':'success','id':new_rowid}
    #删除数据
    def delete(self,select_field:list=('*'),condition_field:list=None,order_by:list=None,limit:str=None,count:bool=True,**kwargs):
        self.test_flag=True
        self.test_print('delete condition_field',condition_field)
        return self.get_put_delete(use_type='delete',select_field=select_field,condition_field=condition_field,order_by=order_by,limit=limit,count=count,**kwargs)
    #假删除数据
    def detete2(self,info=None):
        pass
    #修改数据
    def put(self,put_field_dct=None,select_field:list=('*'),condition_field:list=None,order_by:list=None,limit:str=None,count:bool=True,**kwargs):
        self.test_flag=True
        #put_field_dct : dict {"name":1,"val":3} //要修改的数据 其他的 都是匹配条件  同get

        #{'key1':['val1'],'key2':'val2'}->{'key1':'val1','key2':'val2'}
        put_field_dct={key:put_field_dct[key][0] if isinstance(put_field_dct[key],list) else put_field_dct[key]  for key in put_field_dct}
        return self.get_put_delete(put_field_dct=put_field_dct,use_type='put',select_field=select_field,condition_field=condition_field,order_by=order_by,limit=limit,count=count,**kwargs)
    #查询数据：返回字典
    def get(self,select_field:list=('*'),condition_field:list=None,order_by:list=None,limit:str=None,count:bool=True,**kwargs):
        self.test_flag=False
        # self.test_print('get params:')
        # self.test_print("select_field",select_field)
        # self.test_print("condition_field",condition_field)
        # self.test_print("order_by",order_by)
        # self.test_print("limit",limit)
        # self.test_print("count",count)
        """
        返回值{"count":200,'data':[{'a':33},{'a':55}]}
        select_field 要查询的字段名称 
                    *表示全部字段
                    id 表示只查 id
                    ['id','name']表示只查询id和名字
        condition_field 查询条件
                    None表示条件为空
                    {"id":[1,2,3,4,5,6,7]} 表示查询id为1,2,3,4,5,6
                    ["id",1]表示查询id为1
                    ["id",">",1]表示查询id>1
                    [["id",1]]表示查询id为1
                    [{"id":[1,2,3,4,5,6,7]}] 表示查询id为1,2,3,4,5,6
                    [["id",1],["name","eee"]]表示查询id=1且name=eee
                    [["id",">",1],["name","eee"],["tt","=","333"]]表示查询id>1且name=eee且 tt=333
                    [{"id":[1,2,3,4,5,6,7]},["id",">",1],["name","eee"],["tt","=","333"]]表示查询id为1,2,3,4,5,6且id>1且name=eee且 tt=333
        order_by 条件排序 
                    None表示不排序  
                    "create_time"表示按照create_time 排序(默认为升序) 
                    ["create_time"]表示按照create_time 排序(默认为升序) 
                    ["create_time","desc"]表示按照create_time 排序(降序)
                    [["create_time"]]表示按照create_time 排序(默认为升序) 
                    [["create_time","desc"]]表示按照create_time排序(降序)
                    [["create_time","ASC"],["create_time2","ASC"]]表示按照create_time排序(升序) 再按照 create_time2排序(升序)
        limit  查询限制
                None 表示不限制
                10   表示查询前10
                [10,20] 表示查询10-20
                [1,50,None] 表示 每页查询50条数据  现在查询第一页数据   None可以为任何数,纯凑长度
        count  是否要返回总共有多少条数据(忽略limit)
        ############
        返回值{"count":200,'data':[{'a':33},{'a':55}]}    表示总共有200条数据   现在因为limit只查询了2条数据  数据分别是json格式   
        """
        return self.get_put_delete(use_type='get',select_field=select_field,condition_field=condition_field,order_by=order_by,limit=limit,count=count,**kwargs)
        # values=[]#防sql注入 所有用户上传要放入列表中 然后统一处理
        # #查询字段 field
        # select_field_str=''
        # # self.test_print('################',select_field,type(select_field))
        # select_field=self._del1(select_field)#删除空字符
        # if select_field=='*':#全部字段
        #     select_field_str='*'
        # elif isinstance(select_field,str):#id 表示只查 id
        #     select_field_str=select_field
        # else:
        #     select_field_str+=','.join([field_str for field_str in select_field])#部分字段
        #     # self.test_print('!!!!!!!!!!!!!!!!select_field_str',select_field_str)
        # #查询条件 condition
        # condition_field=self._del1(condition_field)#删除空字符
        # condition_field_str=''
        # if condition_field is None or condition_field==[]:#如果查询条件为空 或者 为[]
        #     pass#跳过
        # elif len(condition_field)==2 and isinstance(condition_field[0],str):#["id",1]表示查询id为1
        #     condition_field_str=' WHERE %s=?'%condition_field[0]
        #     values.append(condition_field[1])
        # elif len(condition_field)==3 and isinstance(condition_field[0],str):#["id",">",1]表示查询id>1
        #     condition_field_str=' WHERE %s%s?'%(condition_field[0],condition_field[1])
        #     values.append(condition_field[2])
        # else:
        #     for item in condition_field:
        #         if len(item)==2:#[["id",1]]表示查询id为1
        #             if condition_field_str=='':condition_field_str=' WHERE '
        #             condition_field_str+="%s=? and "%item[0]
        #             values.append(item[1])
        #         elif len(item)==3:#[["id",">",1],["name","eee"],["tt","=","333"]]表示查询id>1且name=eee且 tt=333
        #             if condition_field_str=='':condition_field_str=' WHERE '
        #             condition_field_str+="%s%s? and "%(item[0],item[1])
        #             values.append(item[2])
        #     condition_field_str = condition_field_str[:-5]#去除末尾的‘ and ’
        # #排序 order by
        # order_by=self._del1(order_by)#删除空字符
        # order_by_str=''
        # if order_by is None or order_by==[]:#表示没有排序
        #     pass#跳过
        # elif isinstance(order_by,str):#"create_time"表示按照create_time 排序(默认为升序)
        #     order_by_str=' ORDER BY %s'%order_by
        # elif len(order_by)==1 and isinstance(order_by[0],str):#["create_time"]表示按照create_time 排序(默认为升序) 
        #     order_by_str=' ORDER BY %s'%order_by[0]
        # elif len(order_by)==2 and isinstance(order_by[0],str):#["create_time","desc"]表示按照create_time 排序(降序)
        #     str_= ' ORDER BY %s %s'%(order_by[0],order_by[1])
        #     order_by_str+=str_
        # else:
        #     for item in order_by:
        #         if len(item)==1:#[["create_time"]]表示按照create_time 排序(默认为升序)
        #             if order_by_str=='':order_by_str=' ORDER BY '
        #             str_='%s,'%item[0]
        #             order_by_str+=str_
        #         if len(item)==2:#[["create_time","desc"]]表示按照create_time排序(降序)
        #             if order_by_str=='':order_by_str=' ORDER BY '
        #             str_='%s %s,'%(item[0],item[1])
        #             order_by_str+=str_
        #     order_by_str = order_by_str[:-1]#去除末尾的‘, ’
        # #查询限制 limit
        # limit_str=''
        # limit_lst=[]
        # if limit is None or limit=='':#None 表示不限制
        #     pass
        # elif isinstance(limit,int):#10   表示查询前10
        #     limit_str=' LIMIT ?'
        #     limit_lst.append(limit)
        # elif len(limit)==2:#[1,50] 表示 每页查询50条数据  现在查询第一页数据
        #     limit_data=[limit[0]*limit[1],(limit[0]+1)*limit[1]] 
        #     limit_str=' LIMIT ?,?'
        #     limit_lst.extend([limit[0]*limit[1],limit[1]])
        # elif len(limit)==3:# [10,20,None]    表示查询10-20 None可以为任何数,纯凑长度
        #     limit_str=' LIMIT ?,?'
        #     limit_lst.extend([limit[0],limit[1]-limit[0]])
            

        # #创建cur和conn
        # # 连接到SQLite数据库
        # conn = sqlite3.connect(self.db_file_path)
        # #将数据转为字典
        # conn.row_factory = self.dict_factory
        # # 创建游标对象
        # cursor = conn.cursor()
        # # 获取查询结果
        # res={}
        # try:
        #     sql="select %s from %s%s%s%s"%(select_field_str,self.table_name,condition_field_str,order_by_str,limit_str)#
            
        #     sql=sql.rstrip()+';'#去除末尾空格并加上';'
        #     new_values=values+limit_lst
        #     # self.test_print('###sql数据',sql)
        #     # self.test_print('###val数据',new_values)
        #     # self.test_print('new_values1',new_values)
        #     cursor.execute(sql,new_values)
        #     info = cursor.fetchall()  # 空则为[]
        #     conn.commit()
        # except Exception as e:
        #     self.test_print(e)
        #     info = []
        # res['data']=info
        # if count is True:#是否要返回总共有多少条数据(忽略limit)
        #     try:
        #         #查询数量 count
        #         sql="select COUNT(*) from %s%s%s"%(self.table_name,condition_field_str,order_by_str)
        #         sql=sql.rstrip()+';'#去除末尾空格并加上';'
        #         # self.test_print('sql2',sql,values)
        #         cursor.execute(sql,values)
        #         info = cursor.fetchall()  # 空则为[]
        #         conn.commit()
        #     except Exception as e:
        #         self.test_print('eeeee',e)
        #         info = []
        #     # self.test_print(info)
        #     # self.test_print(info[0][r"COUNT(*)"])
        #     res['count']=info[0]["COUNT(*)"]
        # # self.test_print('db res',res)
        # conn.close()
        # return res

    def use(self,put_field_dct=None,info=None,use_type='get',select_field:list=('*'),condition_field:list=None,order_by:list=None,limit:str=None,count:bool=True,**kwargs):
        
        # self.test_print('get params:')
        # self.test_print("select_field",select_field)
        # self.test_print("condition_field",condition_field)
        # self.test_print("order_by",order_by)
        # self.test_print("limit",limit)
        # self.test_print("count",count)
        """
        返回值{"count":200,'data':[{'a':33},{'a':55}]}
        put_field_dct 要修改的字段
                    {"name":1,"val":3} 表示修改字段name=1 字段val=3
        select_field 要查询的字段名称 
                    *表示全部字段
                    id 表示只查 id
                    ['id','name']表示只查询id和名字
        condition_field 查询条件
                    None表示条件为空
                    {"id":[1,2,3,4,5,6,7]} 表示查询id为1,2,3,4,5,6
                    ["id",1]表示查询id为1
                    ["id",">",1]表示查询id>1
                    [["id",1]]表示查询id为1
                    [{"id":[1,2,3,4,5,6,7]}] 表示查询id为1,2,3,4,5,6
                    [["id",1],["name","eee"]]表示查询id=1且name=eee
                    [["id",">",1],["name","eee"],["tt","=","333"]]表示查询id>1且name=eee且 tt=333
                    [{"id":[1,2,3,4,5,6,7]},["id",">",1],["name","eee"],["tt","=","333"]]表示查询id为1,2,3,4,5,6且id>1且name=eee且 tt=333
        order_by 条件排序 
                    None表示不排序  
                    "create_time"表示按照create_time 排序(默认为升序) 
                    ["create_time"]表示按照create_time 排序(默认为升序) 
                    ["create_time","desc"]表示按照create_time 排序(降序)
                    [["create_time"]]表示按照create_time 排序(默认为升序) 
                    [["create_time","desc"]]表示按照create_time排序(降序)
                    [["create_time","ASC"],["create_time2","ASC"]]表示按照create_time排序(升序) 再按照 create_time2排序(升序)
        limit  查询限制
                None 表示不限制
                10   表示查询前10
                [10,20] 表示查询10-20
                [1,50,None] 表示 每页查询50条数据  现在查询第一页数据   None可以为任何数,纯凑长度
        count  是否要返回总共有多少条数据(忽略limit)
        ############
        返回值{"count":200,'data':[{'a':33},{'a':55}]}    表示总共有200条数据   现在因为limit只查询了2条数据  数据分别是json格式   
        """
        self.test_print('post,put,delete,get params########1111111#########:',use_type)
        self.test_print('put_field_dct',put_field_dct)
        self.test_print('select_field',select_field)
        self.test_print('condition_field',condition_field)
        self.test_print('order_by',order_by)
        self.test_print('limit',limit)
        self.test_print('count',count)
        self.test_print()
        # self.test_print('getputdelete condition_field',condition_field)
        values=[]#防sql注入 所有用户上传要放入列表中 然后统一处理
        first_str=''
        if use_type=='post':
            self.post(info=info)
        elif use_type=='get':
            #查询字段 field
            select_field_str=''
            # self.test_print('################',select_field,type(select_field))
            select_field=self._del1(select_field)#删除空字符
            if select_field=='*':#全部字段
                select_field_str='*'
            elif isinstance(select_field,str):#id 表示只查 id
                select_field_str=select_field
            else:
                select_field_str+=','.join([field_str for field_str in select_field])#部分字段
            first_str="select %s from %s"%(select_field_str,self.table_name)
            # self.test_print(first_str)
        elif use_type=='delete':
            first_str="DELETE from %s"%self.table_name
        elif use_type=='put':
            ##############################字段被修改时 自动添加当前字段 和 当前时间  step 2/2
            for item in self.update_modify_time:
                put_field_dct[item]=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            put_names=list(put_field_dct.keys())
            put_values=[put_field_dct[name] for name in put_names]
            update_field_str=','.join([key+'=?' for key in put_names])

            first_str="UPDATE %s SET %s"%(self.table_name,update_field_str) 
            first_str_select="select %s from %s"%(self.id_name,self.table_name)
            # self.test_print('!!!!!!!!!!!!!!!!select_field_str',select_field_str)
        #查询条件 condition
        # self.test_print('######1',condition_field)
        condition_field=self._del1(condition_field)#删除空字符
        # self.test_print('######2',condition_field)
        
                    # None表示条件为空
                    # {"id":[1,2,3,4,5,6,7]} 表示查询id为1,2,3,4,5,6
                    # ["id",1]表示查询id为1
                    # ["id",">",1]表示查询id>1
                    # [["id",1]]表示查询id为1
                    # [{"id":[1,2,3,4,5,6,7]}] 表示查询id为1,2,3,4,5,6
                    # [["id",1],["name","eee"]]表示查询id=1且name=eee
                    # [["id",">",1],["name","eee"],["tt","=","333"]]表示查询id>1且name=eee且 tt=333
                    # [{"id":[1,2,3,4,5,6,7]},["id",">",1],["name","eee"],["tt","=","333"]]表示查询id为1,2,3,4,5,6且id>1且name=eee且 tt=333
        condition_field_str=''
        if condition_field in ([],None,{}):#如果查询条件为空 或者 为[]
            pass#跳过
        elif isinstance(condition_field,dict):
            key=list(condition_field.keys())[0]
            vals=list(condition_field.values())[0]
            condition_field_str=' WHERE %s in (%s)'%(key,','.join(['?'for item in vals]))
            values.extend(vals)
        elif isinstance(condition_field,list) and len(condition_field)==1 and isinstance(condition_field[0],dict):
            key=list(condition_field[0].keys())[0]
            vals=list(condition_field[0].values())[0]
            condition_field_str=' WHERE %s in (%s)'%(key,','.join(['?'for item in vals]))
            values.extend(vals)
        elif len(condition_field)==2 and isinstance(condition_field[0],str):#["id",1]表示查询id为1
            condition_field_str=' WHERE %s=?'%condition_field[0]
            values.append(condition_field[1])
        elif len(condition_field)==3 and isinstance(condition_field[0],str):#["id",">",1]表示查询id>1
            condition_field_str=' WHERE %s%s?'%(condition_field[0],condition_field[1])
            values.append(condition_field[2])
        else:
            for item in condition_field:
                if isinstance(item,dict):#{"id":[1,2,3,4,5,6,7]} 表示查询id为1,2,3,4,5,6
                    if condition_field_str=='':condition_field_str=' WHERE '
                    key=list(item.keys())[0]
                    vals=list(item.values())[0]
                    values.extend(vals)
                    condition_field_str+="%s in (%s) and "%(key,','.join(['?'for item in vals]))
                elif len(item)==2:#[["id",1]]表示查询id为1
                    if condition_field_str=='':condition_field_str=' WHERE '
                    condition_field_str+="%s=? and "%item[0]
                    values.append(item[1])
                elif len(item)==3:#[["id",">",1],["name","eee"],["tt","=","333"]]表示查询id>1且name=eee且 tt=333
                    if condition_field_str=='':condition_field_str=' WHERE '
                    condition_field_str+="%s%s? and "%(item[0],item[1])
                    values.append(item[2])
            condition_field_str = condition_field_str[:-5]#去除末尾的‘ and ’
        # self.test_print('condition_field_str',condition_field,condition_field_str)
        #排序 order by
        order_by=self._del1(order_by)#删除空字符
        order_by_str=''
        if order_by is None or order_by==[]:#表示没有排序
            pass#跳过
        elif isinstance(order_by,str):#"create_time"表示按照create_time 排序(默认为升序)
            order_by_str=' ORDER BY %s'%order_by
        elif len(order_by)==1 and isinstance(order_by[0],str):#["create_time"]表示按照create_time 排序(默认为升序) 
            order_by_str=' ORDER BY %s'%order_by[0]
        elif len(order_by)==2 and isinstance(order_by[0],str):#["create_time","desc"]表示按照create_time 排序(降序)
            str_= ' ORDER BY %s %s'%(order_by[0],order_by[1])
            order_by_str+=str_
        else:
            for item in order_by:
                if len(item)==1:#[["create_time"]]表示按照create_time 排序(默认为升序)
                    if order_by_str=='':order_by_str=' ORDER BY '
                    str_='%s,'%item[0]
                    order_by_str+=str_
                if len(item)==2:#[["create_time","desc"]]表示按照create_time排序(降序)
                    if order_by_str=='':order_by_str=' ORDER BY '
                    str_='%s %s,'%(item[0],item[1])
                    order_by_str+=str_
            order_by_str = order_by_str[:-1]#去除末尾的‘, ’
        #查询限制 limit
        limit_str=''
        limit_lst=[]
        if limit is None or limit=='':#None 表示不限制
            pass
        elif isinstance(limit,int):#10   表示查询前10
            limit_str=' LIMIT ?'
            limit_lst.append(limit)
        elif len(limit)==2:#[1,50] 表示 每页查询50条数据  现在查询第一页数据
            limit_data=[limit[0]*limit[1],(limit[0]+1)*limit[1]] 
            limit_str=' LIMIT ?,?'
            limit_lst.extend([limit[0]*limit[1],limit[1]])
        elif len(limit)==3:# [10,20,None]    表示查询10-20 None可以为任何数,纯凑长度
            limit_str=' LIMIT ?,?'
            limit_lst.extend([limit[0],limit[1]-limit[0]])
            
        self.test_print('post,put,delete,get params########222222222#########:',use_type)
        self.test_print('put_field_dct',put_field_dct)
        self.test_print('select_field',select_field)
        self.test_print('condition_field',condition_field)
        self.test_print('order_by',order_by)
        self.test_print('limit',limit)
        self.test_print('count',count)

        self.test_print()
        #创建cur和conn
        # 连接到SQLite数据库
        conn = sqlite3.connect(self.db_file_path)
        #将数据转为字典
        conn.row_factory = self.dict_factory
        # 创建游标对象
        cursor = conn.cursor()
        # 获取结果
        res={}
        try:
            sql=first_str+"%s%s%s"%(condition_field_str,order_by_str,limit_str)#

            sql=sql.rstrip()+';'#去除末尾空格并加上';'
            new_values=values+limit_lst
            if use_type=='put':
                new_values=put_values+new_values
            self.test_print('###sql数据',sql)
            self.test_print('###val数据',new_values)
            # self.test_print('new_values1',new_values)
            cursor.execute(sql,new_values)
            if use_type =='delete':
                # 获取删除的数据数量
                data_count = cursor.rowcount
                res['count']=data_count
            elif use_type =='put':
                sql=first_str_select+"%s%s%s"%(condition_field_str,order_by_str,limit_str)#

                sql=sql.rstrip()+';'#去除末尾空格并加上';'
                
                cursor.execute(sql,values+limit_lst)
                self.test_print('###sql数据',sql)
                self.test_print('###val数据',values+limit_lst)
                info = cursor.fetchall()  # 空则为[]
                # 使用lastrowid()获取修改数据的自增主键值
                self.test_print('put_new info',info)
                res['id'] = info[0][self.id_name]
                self.test_print('put new id',res['id'])
            elif use_type=='get':
                info = cursor.fetchall()  # 空则为[]
                res['data']=info
            conn.commit()
        except Exception as e:
            if use_type=='get':
                res['data']=[]
            self.test_print('eeeee',e)
            res['type']='error'
            res['message']=str(e)
            return res
        if use_type=='get':
            if count is True:#是否要返回总共有多少条数据(忽略limit)
                try:
                    #查询数量 count
                    sql="select COUNT(*) from %s%s%s"%(self.table_name,condition_field_str,order_by_str)
                    sql=sql.rstrip()+';'#去除末尾空格并加上';'
                    # self.test_print('sql2',sql,values)
                    cursor.execute(sql,values)
                    info = cursor.fetchall()  # 空则为[]
                    conn.commit()
                except Exception as e:
                    self.test_print('eeeee',e)
                    info = []
                # self.test_print(info)
                # self.test_print(info[0][r"COUNT(*)"])
                res['count']=info[0]["COUNT(*)"]
        # self.test_print('db res',res)
        conn.close()
        self.test_print('post,put,delete,get params########333333333333#########:',res)
        return res
def __test__delete():#测试 #删
    res=b.get() 
    # self.test_print(res)
    print('当前数据',res['count'],'条')
    dct={'name':'刚插入的数据','color_code':'#ff1212','notes':'大锅饭的大锅有10米长10米宽'}
    print("插入一条数据",b.post(dct),dct)
    res=b.get()
    print('当前数据',res['count'],'条')
    print('最后的数据为:',res['data'][-1])
    lst=["name","刚插入的数据"]
    print(f'删除了{b.delete(condition_field=lst)}条数据,删除的数据条件为{lst}')
    print('当前数据',res['count'],'条')
def __test__put():#测试 #改
    
    res=b.get() 
    print(res)
    print('当前数据',res['count'],'条')
    dct={'name':'123','color_code':'#ff1212','notes':'大锅饭的大锅有10米长10米宽'}
    # print("插入一条数据",b.post(dct),dct)
    res=b.get()
    print('当前数据',res['count'],'条')
    print('最后的数据为:',res['data'][-1])
    lst=["name","123"]
    lst2={'name':'666','color_code':'#111111'}
    print(f'修改了{b.get(put_field_dct=lst2,condition_field=lst)}条数据,修改的数据条件为{lst},修改的数据为{lst2}')
    res=b.get()
    print('当前数据',res['count'],'条')
    print('最后的数据为:',res['data'][-1])
def __test__get():#测试 #查
            
    # #创建虚拟数据N条
    # n=b.create_virtual_data()   

    # print('创建虚拟数据',n,'条')
    #查询所有数据
    res=b.select_field_all() 
    
    print('当前数据',res,'条')
    # print("select_field ",'*表示全部字段',b.get(select_field='*',limit=2))
    # print("select_field ",'id 表示只查 id',b.get(select_field='id',limit=2))
    # print("select_field ","['id','name']表示只查询id和名字",b.get(select_field=['id','id2'],limit=2))
    
    # print("condition_field",'None表示条件为空',b.get(condition_field=None,limit=2))
    # print("condition_field",'["name",33]表示查询name为33',b.get(condition_field=["name",33],limit=2))
    # print("condition_field",'["name","33"]表示查询name为"33"',b.get(condition_field=["name","33"],limit=2))
    # print("condition_field",'["id",">",1]表示查询id>1',b.get(condition_field=["id",">",1],limit=2))
    # print("condition_field",'[["id",1]]表示查询id为1',b.get(condition_field=[["id","1"]],limit=2))
    # print("condition_field",'[["id",1],["id2",1]]表示查询id=1且id2=1',b.get(condition_field=[["id",1],["id2","1"]],limit=2))
    # print("condition_field",'[["id",">",1],["id2","2"],["create_time",">",0]]表示查询id>1且id2=2且create_time>0',b.get(condition_field=[["id",">",1],["id2","2"],["create_time",">",0]],limit=2))
    # condition_field=[["id",">",7],{'id':['6','12',14]}]
    # print("condition_field",condition_field,b.get(select_field=['id','name'],condition_field=condition_field))   
    # condition_field=[{'id': [1, '我好羡慕风啊羡慕雨', '我好羡慕风啊羡慕雨', 1]}]
    # print("condition_field",condition_field,b.get(select_field=['id', 'name', 'color_code'],condition_field=condition_field))

    
    # print("order_by",'None表示不排序 ',b.get(condition_field=None,limit=2))
    # print("order_by",'"create_time"表示按照create_time 排序(默认为升序) ',b.get(order_by='create_time',limit=2))
    # print("order_by",'["create_time"]表示按照create_time 排序(默认为升序) ',b.get(order_by=["create_time"],limit=2))
    # print("order_by",'["create_time","desc"]表示按照create_time 排序(降序)',b.get(select_field="create_time",order_by=["create_time","DESC"],limit=2))
    # print("order_by",'[["create_time"]]表示按照create_time 排序(默认为升序) ',b.get(select_field="create_time",order_by=[["create_time"]],limit=2))
    # print("order_by",'[["create_time","desc"]]表示按照create_time排序(降序)',b.get(select_field="create_time",order_by=[["create_time","DESC"]],limit=2))
    # print("order_by",'[["create_time","ASC"],["create_time2","ASC"]]表示按照create_time排序(升序) 再按照 create_time2排序(升序)',b.get(select_field="create_time",order_by=[["create_time","ASC"],["modify_time","ASC"]],limit=2))
        
        
        
    # print("limit",'None 表示不限制',len(b.get(limit=None)['data']))
    print("limit",'10   表示查询前10',len(b.get(limit=[0,20])['data']))
    # print("limit",'[10,20] 表示查询10-20',len(b.get(limit=[10,20])['data']))
    # print("limit",'[1,50,None] 表示 每页查询50条数据  现在查询第一页数据   None可以为任何数,纯凑长度',len(b.get(limit=[1,50,None])['data']))

def __test__post():#测试 #增
    info={'color_code': '#ffffff', 'name': '1', 'breed_id': '1', 'ee6_1': '1', 'ee2_1': '1', 'ee2_2': '1', 'ee2_3': '1', 'ee3_1': '1', 'ee3_2': '1', 'ee3_3': '11', 'ee3_4': '1', 'ee3_5': '1', 'ee3_6': '1', 'ee3_7': '1', 'ee3_8': '1', 'ee4_1': '11', 'ee5_1': '1', 'ee5_2': '1', 'ee5_4': '1', 'ee5_5': '1', 'ee5_7': '1', 'ee5_8': '1', 'ee6_2': '1', 'ee7_1': '1', 'ee7_2': '1', 'ee7_3': '1', 'ee7_4': '1', 'ee7_5': '1', 'ee8_1': '1', 'ee10_1': '11', 'notes': '1', 'ee5_3': '1'}
    res=b.get()
    print('当前数据',res['count'],'条')
    print("插入一条数据",b.post(info=info))
    
    res=b.get() 
    print('当前数据',res['count'],'条')
    print('最后的数据为:',res['data'][-1])
    # t=time.time()
    # count=10000
    # temp=[['玫瑰红','#ff1212','大锅饭的大锅有10米长10米宽']]*count
    # data=[['name','color_code','notes']]+temp
    # b.post(data)
    # print(f'列表的方式 插入{count}条数据花了{time.time()-t}秒')
    
    # res=b.get() 
    # print('当前数据',res['count'],'条')
    # t=time.time()
    # count2=count
    # temp=[{'name':'玫瑰红','color_code':'#ff1212','notes':'大锅饭的大锅有10米长10米宽'}]*count
    # b.post(data)
    # print(f'字典的方式 插入{count2}条数据花了{time.time()-t}秒')

    # res=b.get() 
    # print('当前数据',res['count'],'条')
class a_1_0_1_0_0(base_class):
    @classmethod
    def test_server(c,db_data,db_dir):
        db_data=db_data['dict']['1']['dict']
        c.dbs={}
        for idx in db_data.keys():
            data=db_data[idx]
            c.dbs[data['base_info']['deepcopy_data']['en_name']]=a_1_0_1_0_0_base2(db_data=data,
                                                                                      db_dir_path=db_dir,#位于用户项目 当前流程文件夹下的 db_dir下
                                                                                      )
        c._recv_http_test()#与其他进程进行通信
    @classmethod
    def handle_http_test(self,http_obj,type_param,data_param):
        print("type_param,data_param",type_param,data_param)
        db_name=type_param
        http_obj.write(self.dbs[db_name].use(**data_param))
    def run_server(self,callback_lst=list()):
        self.db_data=self.process_input.get("db_data")
        self.dbs={}
        db_data=self.db_data['dict']['1']['dict']
        for idx in db_data.keys():
            data=db_data[idx]
            self.dbs[data['base_info']['deepcopy_data']['en_name']]=a_1_0_1_0_0_base2(db_data=data,
                                                                                      db_dir_path=self.public_data.get("db_dir"),#位于用户项目 当前流程文件夹下的 db_dir下
                                                                                      )
        
        self._recv_http()#与其他进程进行通信
    def handle_http(self,http_obj,type_param,data_param):
        db_name=type_param
        http_obj.write(self.dbs[db_name].use(**data_param))
if __name__ == '__main__':

    config={"base_info": {
        "index": 2
    },
    "dict": {
        "1": {
            "base_info": {
                "vue_name": "a_1_0_2_26_1",
                "index": "1",
                "deepcopy_data": {
                    "name": "数据库列表"
                }
            },
            "dict": {
                "1": {
                    "base_info": {
                        "index": "5",
                        "vue_name": "a_1_0_2_28_1",
                        "deepcopy_data": {
                            "index": 1,
                            "en_name": "user_db",
                            "ch_name": "用户库",
                            "note": "",
                            "ps": {
                                "1": {
                                    "k": "params1",
                                    "v": "value1"
                                }
                            },
                            "name": "user_db[用户库]"
                        }
                    },
                    "dict": {
                        "1": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "id",
                                    "field_type": "INTEGER",
                                    "default_value": 0,
                                    "ch_name": "",
                                    "index_type": "PRIMARY KEY",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "id[]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "2": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "user_name",
                                    "field_type": "TEXT",
                                    "default_value": "",
                                    "ch_name": "用户名",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "user_name[用户名]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "3": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "passwd",
                                    "field_type": "TEXT",
                                    "default_value": "",
                                    "ch_name": "密码",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "passwd[密码]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "4": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "level",
                                    "field_type": "INTEGER",
                                    "default_value": 0,
                                    "ch_name": "权限等级",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "level[权限等级]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        },
                        "5": {
                            "base_info": {
                                "deepcopy_data": {
                                    "index": 1,
                                    "en_name": "create_id",
                                    "field_type": "INTEGER",
                                    "default_value": 0,
                                    "ch_name": "创建人id",
                                    "index_type": "None",
                                    "note": "",
                                    "ps": {
                                        "1": {
                                            "k": "params1",
                                            "v": "value1"
                                        }
                                    },
                                    "name": "create_id[创建人id]"
                                },
                                "vue_name": "a_1_0_2_29_1",
                                "index": 0
                            },
                            "dict": {}
                        }
                    }
                }
            }
        },
        "2": {
            "base_info": {
                "vue_name": "a_1_0_2_27_1",
                "index": 0,
                "deepcopy_data": {
                    "name": "搜索数据库"
                }
            },
            "dict": {}
        }
    }
}
    #取出来color_db的数据
    b=a_1_0_1_0_0.test_server(config,os.path.dirname(os.path.abspath(__file__)))
    
